package com.qkl.xiatang.app.service.wvp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qkl.xiatang.app.config.AppConfig;
import com.qkl.xiatang.app.entity.wvp.WvpDeviceEntity;
import com.qkl.xiatang.app.mapper.WvpDeviceMapper;
import com.qkl.xiatang.app.service.pc.PCService;
import com.qkl.xiatang.app.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class WvpChannelService {

    /**
     * 刷新通道时间间隔
     */
    private static final int CHANNEL_REFRESH_INTERVAL = 60;

    @Autowired
    private PCService pcService;

    @Autowired
    private WvpDeviceMapper wvpDeviceMapper;

    @Autowired
    private AppConfig appConfig;


    private long channelRefreshTime = 0;

    private boolean isChannelRefresh(){
        if( !appConfig.isChannelRefresh()){
            return false;
        }
        long currTime = System.currentTimeMillis();
        long refreshTime = channelRefreshTime * CHANNEL_REFRESH_INTERVAL * 60 * 1000;
        if( currTime > refreshTime ){
            channelRefreshTime = currTime;
            return true;
        }
        return false;
    }

    public void channelRefresh(String companyId){
        if( !this.isChannelRefresh()){
            return;
        }
        List<WvpDeviceEntity> deviceList = wvpDeviceMapper.selectList(new QueryWrapper<WvpDeviceEntity>().eq("company_id",companyId));
        try {
            channelRefresh(deviceList);
        }catch (Exception e){
            log.error("=====channelRefresh error:",e);
        }

    }
    private void channelRefresh(List<WvpDeviceEntity> deviceList){
        if(ObjectUtils.isEmpty(deviceList)){
            return;
        }
        for (WvpDeviceEntity device : deviceList){
            pcService.channelRefresh(device.getDeviceId());
        }
    }
}
